<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="创建人" prop="createName">
                <el-input v-model="queryParams.createName" placeholder="请输入指导人" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请选择" clearable @keyup.enter.native="handleQuery">
                    <el-option key="0" label="未反馈" value="0" />
                    <el-option key="1" label="已反馈" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="borrowType">
                <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="guidanceList" :height="tableHeight" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="指导人" align="center" prop="createName" :show-overflow-tooltip="true" />
            <el-table-column label="指导内容" align="center" prop="content" :show-overflow-tooltip="true">
            </el-table-column>
<!--             
    //0 暂存  1提交  2反馈 


//1未反馈  2反馈 -->
            <el-table-column label="状态" align="center" prop="state" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <p v-if="scope.row.state == 2">
                        已反馈
                    </p>
                    <p v-if="scope.row.state == 1">
                        未反馈
                    </p>
                </template>
            </el-table-column>
            <!-- <el-table-column label="租户编码" align="center" prop="tenantCode" :show-overflow-tooltip="true" /> -->
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-document" @click="handleDetail(scope.row)" v-hasPermi="['archive:supervision:guidanceNew:xq']">详情</el-button>
                    <el-button type="text" icon="el-icon-chat-dot-round" @click="handleDiscuss(scope.row)" v-hasPermi="['archive:supervision:guidanceNew:tl']">讨论</el-button>
                    <el-button v-if="scope.row.state == 1" type="text" icon="el-icon-edit"
                        @click="handleFeedback(scope.row)" v-hasPermi="['archive:supervision:guidanceNew:fk']">反馈</el-button>
                    <el-button v-if="scope.row.state == 2" type="text" icon="el-icon-document"
                        @click="handleFeedbackContent(scope.row)" v-hasPermi="['archive:supervision:guidanceNew:fknr']">反馈内容</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        <el-dialog :title="title" :visible.sync="open" width="35%" style="margin-top:8%" append-to-body
            :before-close="closeDelDialog">
            <template>
                <el-form ref="form" :model="form" label-width="80px">
                    <el-row >
                        <el-col :span="24">
                            <el-input type="textarea" :autosize="{ minRows: 6 }" :readonly="istype == 1 ? true : false"
                                :rows="2" placeholder="请输入内容" v-model="feedback">
                            </el-input>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitFeedback" v-if="istype == 0">确 定</el-button>
                    <el-button @click="closeDelDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>



        <el-dialog title="查看详情" :visible.sync="openSupervises" width="70%" append-to-body :before-close="closeDelDialog1">
            <template>
                <div>
                    <el-form ref="form" :model="form" label-width="80px">
                        <el-row ref="refbut" style="width:80%;margin:0 auto">
                            <el-col :span="24" class="df transf-title-row">
                                <el-form-item label="指导建议">
                                    <editor v-model="form.content" :min-height="400" />
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="上传附件">
                                    <div v-for="(item,index) in uploadList" :key="index" style="display: flex; margin-left: 1%">
                                        <span style="padding: 0 5px">{{ item.docName }}</span>
                                        <p v-if="isFbState" style="border-bottom: 1px solid red;">
                                            <span v-for="(i, idx) in renyuanOptions" :key="idx">
                                                {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                                            </span>
                                        </p>
                                        <el-button type="text" @click="onPreviewTap(item)"
                                            style="margin-left:10px">预览</el-button>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </template>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDelDialog1">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 预览 -->
        <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="45%" append-to-body>
            <!--
         文件预览
         1、修改添加文件预览istype="1"
         2、查看组件详情istype="2"
         -->
            <FilePreview v-if="item" :item="item" :istype="previewIstype"></FilePreview>
        </el-dialog>

        <!-- 讨论 -->
        <el-dialog title="讨论" :visible.sync="discussOpen" width="25%" append-to-body :before-close="closeDiscuss"
            @opened="scrollToBottom" @closed="stopInterval">
            <el-card class="box-card">
                <div class="head" ref="messageContainer">
                    <div v-for="(item, index) in messages" :key="index" class="message">
                        <div v-if="item.float == 'left'" class="message-left">
                            <div class="message-time-left">{{ item.creator }} {{ item.time }}</div>
                            <div class="message-text-left">{{ item.content }}</div>
                        </div>
                        <div v-else class="message-right">
                            <div class="message-time-right">{{ item.time }} {{ item.creator }}</div>
                            <div class="message-text-right">{{ item.content }}</div>
                        </div>
                    </div>
                </div>
                <div class="bottom" v-show="isShowSend">
                    <el-input v-model="message" style="width: 75%" />
                    <el-button type="primary" style="margin-left: 1%" @click="sendMessage">发送</el-button>
                </div>
            </el-card>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDiscuss">关 闭</el-button>
            </div>
        </el-dialog>


        <!--start  组件详情 -->
        <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" :celldbData="celldbData"
            @detailsHandleClose="detailsHandleClose">
        </jianDetailsOpen>
        <!--end 组件详情 -->
        <!-- start 组卷\项目详情 -->
        <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
            @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
        <!-- end 组卷\项目详情 -->
    </div>
</template>
  
<script>

import { uploadFileList } from "@/api/archive/supervision/supervisesNew/supervisesNew.js";
import { listGuidanceList, guidanceDetail, updateGuidanceList,getDiscussList,addDiscuss} from "@/api/archive/supervision/guidanceNew/guidanceNew.js"
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
import { getLastIndexOf } from "@/utils";
import { getthbytreenodeHeaderList } from "@/api/archive/warehouseManagement/upDownShelves";
import jianDetailsOpen from "@/components/componentsJianDetails";
import juanDetailsOpen from "@/components/componentsJuanDetails";
import estimateTableHeight from "@/mixins/estimateTableHeight";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
    getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
    components: { FilePreview, jianDetailsOpen, juanDetailsOpen },
    mixins: [estimateTableHeight],// 混入方法
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            total1: 0,
            // archiveBorrowCar表格数据
            guidanceList: [],
            // 弹出层标题
            title: "",
            istype: 0,
            // 是否显示弹出层
            open: false,
            //对象
            supervision: {
                id: "",
                feedbackContent: undefined,
                state: undefined

            },
            minRows: '',
            feedback: undefined,
            openSupervises: false,

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                createName: null,
                state: null
            },
            queryParams1: {
        pageNum: 1,
        pageSize: 10,
        guidanceId:undefined
      },
            dateRange: [],
            // 表单参数
            form: {
                id: undefined,
                content: undefined,
                daIds: undefined
            },
            // 表单校验
            rules: {
            },

            uploadList: [],
            // 预览标题
            previewTitle: '',
            previewOpen: false,
            item: '',
            previewIstype: '1',
            // 讨论
            discussOpen: false,
            messages: [],
            message: undefined,
            tooltipOpen: true,
            formId: '',
            isShowSend: false,
            intervalId: null, // 定时器ID
            // 获取row的key值
            getRowKeys(row) {
                return row.id;
            },
            // 要展开的行，数值的元素是row的key值
            expands: [],
            jianDetailsOpen: false,//件详情弹窗
            juanDetailsOpen: false,//卷详情弹窗
            renyuanOptions: [],//密级下拉列表
            isFbState: false,
        };
    },
    created() {
        this.getList();
        fbstat().then(res => {  //false=不是分保，true=是分保 
            this.isFbState = res.data
            if (this.isFbState) {
                //密级下拉列表
                getDicts_archive("MJ").then(res => { //人员密级
                    getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
                        console.log(resdata, "------------------------")
                        var mjdata = [];
                        for (var i in resdata.data) {
                            for (var j in res.data) {
                                if (resdata.data[i].daMj == res.data[j].dictValue) {
                                    mjdata.push(res.data[j])
                                }
                            }
                        }

                        this.renyuanOptions = mjdata
                        console.log(this.renyuanOptions, "------------------------------------------")

                    })
                })
            }
        })
    },
    methods: {
        /** 查询archiveBorrowCar列表 */
        getList() {
            this.loading = true;
            listGuidanceList(this.queryParams).then(response => {
                this.guidanceList = response.rows;
                for (let i = 0; i < response.rows.length; i++) {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(response.rows[i].content, 'text/html');
                    this.guidanceList[i].content = doc.body.textContent || ""
                }
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                feedback: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            if (this.dateRange != null) {
                if (this.dateRange.length != 0) {
                    this.queryParams.createTime = this.dateRange[0].toString()
                    this.queryParams.edCreateTime = this.dateRange[1].toString()
                }
            }
            this.getList();
            this.queryParams.createTime = ""
            this.queryParams.edCreateTime = ""

        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.carId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        }, closeDelDialog() {
            this.open = false
            /*   this.closeDelDialog=false
               this.$emit("printCancel")*/
        },
        handleFeedback(row) {
            this.istype = 0;
            this.open = true;
            this.title = "反馈";
            this.feedback = undefined;
            this.supervision = {};
            this.supervision.id = row.id;
            this.supervision.state = 2;

        },
        submitFeedback() {
            if (this.feedback == undefined) {
                this.$modal.msgWarning("请输入反馈内容");
            } else {
                const regex = /^\s*$/;
                if (regex.test(this.feedback)) {
                    this.$message.error('不能输入全部空格');
                    return false;
                }
                this.supervision.feedbackContent = this.feedback;
                updateGuidanceList(this.supervision).then(response => {
                    this.$modal.msgSuccess("反馈成功");
                    this.open = false;
                    this.getList();
                });
            }
        },
        handleFeedbackContent(row) {
            this.istype = 1;
            this.feedback = row.feedbackContent;
            this.open = true;
            this.title = "反馈内容";
        },

        //查看详情
        handleDetail(row) {
            const id = row.id
            guidanceDetail({ id: id }).then(resposne => {
                this.reset1();
                this.form = resposne.data;
                this.queryParams1.guidanceId = id
                this.getFileList()
                this.openSupervises = true;
            })

        }, reset1() {
            this.form = {
                id: undefined,
                content: undefined,
                daIds: undefined
            }
        }, closeDelDialog1() {
            this.openSupervises = false
            this.queryParams1 = {
                pageNum: 1,
                pageSize: 10,
                guidanceId: undefined
            }
            /*   this.closeDelDialog=false
               this.$emit("printCancel")*/
        },
        getFileList() {
            uploadFileList({ guidanceId: this.queryParams1.guidanceId }).then(response => {
                this.uploadList = response.rows
            })
        },
        // 预览
        onPreviewTap(item) {
            this.previewTitle = item.docName
            this.previewOpen = true
            this.item = item
        },
        handleDiscuss(row) {
            const id = row.id
            this.formId = id
            if (row.state == '2') {
                this.isShowSend = false
            } else {
                this.isShowSend = true
            }
            this.getDiscuss(id)
        },
        getDiscuss(id) {
            getDiscussList({ guidanceId: id }).then(response => {
                console.log(response)
                this.messages = []
                for (let i = 0; i < response.rows.length; i++) {
                    if (response.rows[i].createId == response.rows[i].loginId) {
                        this.messages.push({
                            content: response.rows[i].discussionContent,
                            time: response.rows[i].createTime,
                            float: 'right',
                            creator: response.rows[i].createName
                        })
                    } else {
                        this.messages.push({
                            content: response.rows[i].discussionContent,
                            time: response.rows[i].createTime,
                            float: 'left',
                            creator: response.rows[i].createName
                        })
                    }
                }
                this.discussOpen = true
            })
        },
        scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messageContainer;
                container.scrollTop = container.scrollHeight;
            });
            // 打开页面每5分钟刷新一次消息列表
            this.intervalId = setInterval(() => {
                this.getDiscuss(this.formId)
            }, 5 * 60 * 1000); // 每5分钟 = 5 * 60秒 * 1000毫秒
        },
        stopInterval() {
            console.log('结束了')
            clearInterval(this.intervalId);
        },
        closeDiscuss() {
            this.discussOpen = false
            this.messages = []
            this.message = ''
            this.formId = ''
        },
        // 发送
        sendMessage() {
            console.log(this.message, this.formId)
            this.form = {
                discussionContent: this.message,
                guidanceId: this.formId
            }
            addDiscuss(this.form).then(response => {
                this.message = ''
                this.messages = []
                this.getDiscuss(this.formId)
            })
        },
        //关闭详情页面
        detailsHandleClose() {
            this.jianDetailsOpen = false;
            this.juanDetailsOpen = false;
        },
        celldblclick(row) {
            console.log(row, '------------------')
            var level = "";
            if (getLastIndexOf(row.subTableName) == "F") {  //F 件
                level = 0
            } else if (getLastIndexOf(row.subTableName) == "V") { //卷
                level = 1
            } else { //项目
                level = 3
            }
            const menuId = this.$route.meta.menuId
            getthbytreenodeHeaderList(
                {
                    categoryId: row.categoryId, menuId: menuId, subTableName: row.subTableName
                }
            ).then(response => {
                var tableHeaderList = response.rows
                this.celldbData = {
                    id: row.daId,
                    categoryId: row.categoryId,
                    menuId: menuId,
                    sub_table_name: row.subTableName,
                    label: row.title,
                    level: level,
                    ifSub_table_name: row.subTableName,
                    isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
                    tableHeaderList: tableHeaderList
                }
                this.$nextTick(() => {
                    if (getLastIndexOf(row.subTableName) == "F") {  //F 进入件详情
                        this.jianDetailsOpen = true;
                    } else { //进入卷详情 和项目详情
                        this.juanDetailsOpen = true
                    }
                })
            })
        },
    }
};
</script>
  
<style lang="scss" scoped>
.box-card {
    width: 90%;
    margin-left: 5%;
    height: 500px;
    position: relative;
}

.head {
    height: 440px;
    overflow-y: auto;
    /* 设置垂直滚动条 */
}

.bottom {
    position: absolute;
    bottom: 1%;
    width: 100%;
}

.message {
    margin-bottom: 10px;

    .message-left {
        flex-direction: column;
    }

    .message-right {
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: flex-end;
    }

    .message-text-left {
        background-color: #f2f2f2;
        padding: 5px;
        border-radius: 5px;
        display: inline-block;
        max-width: 80%;
    }

    .message-time-left {
        font-size: 12px;
        color: #999;
        margin-left: 5px;
    }

    .message-text-right {
        background-color: #e1eaff;
        padding: 5px;
        border-radius: 5px;
        display: inline-block;
        max-width: 80%;
        float: right;
    }

    .message-time-right {
        font-size: 12px;
        color: #999;
        margin-right: 5px;
        float: right;
    }
}
</style>
  